package repository

import (
	"geektime-go/week2/homework/domain"
	"geektime-go/week2/homework/repository/dao"
	"time"
)

type UserRepo struct {
	dao *dao.UserDao
}

func NewUserRepo(dao *dao.UserDao) *UserRepo {
	return &UserRepo{dao: dao}
}

func (repo *UserRepo) Create(user domain.User) error {
	return repo.dao.Insert(dao.User{
		Email:    user.Email,
		Password: user.Password,
	})
}

func (repo *UserRepo) FindByEmail(email string) (domain.User, error) {
	user, err := repo.dao.FindByEmail(email)
	return domain.User{
		Id:       user.Id,
		Email:    user.Email,
		Password: user.Password,
	}, err
}

func (repo *UserRepo) FindById(id int64) (domain.User, error) {
	user, err := repo.dao.FindById(id)
	return domain.User{
		Email:        user.Email,
		NickName:     user.NickName,
		BirthDay:     time.UnixMilli(user.BirthDay),
		Introduction: user.Introduction,
	}, err
}

func (repo *UserRepo) Update(user domain.User) (int64, error) {
	return repo.dao.Update(dao.User{
		Id:           user.Id,
		NickName:     user.NickName,
		BirthDay:     user.BirthDay.UnixMilli(),
		Introduction: user.Introduction,
	})
}
